package com.example.remoteassistance;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/*
*主界面
* 功能：刷新用户列表、请求远程协助
 */
public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    //用户列表刷新视图
    private RefreshableView mRefreshableView;
    //用户列表视图
    private ListView mListView;
    //用户列表
    private List<String> mUserlist;
    //用户列表下标变量
    private int mExpandedMenuPos = -1;
    //用户列表适配器
    private UserListAdapter mUserListAdapter;

    //主机id
    private String mid;
    //从机id
    private String sid;

    //数据通信websocket客户端
    private MessageWebSocketClient mMessageWebSocketClient;
    //数据通信websocket服务
    private MessageWebSocketService mMessageWebSocketService;
    //数据通信websocket服务连接
    private final ServiceConnection mMessageWebSocketServiceConnection = new ServiceConnection() {
        //连接成功
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            mMessageWebSocketService = ((MessageWebSocketService.MessageWebSocketBinder) iBinder).getService();
            mMessageWebSocketClient = MessageWebSocketService.mMessageWebSocketClient;
            Log.d("TAG", "onServiceConnected");
        }
        //断开连接
        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            if (mMessageWebSocketService != null) {
                mMessageWebSocketService = null;
            }
            Log.d(TAG, "onServiceDisconnected");
        }
    };

    //数据通信广播接收器
    private class MessageBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            //通过intent接收数据
            String message = intent.getStringExtra("message");
            try {
                ObjectMapper mapper = new ObjectMapper();
                //读取json数据包
                MessagePacket packet = mapper.readValue(message, MessagePacket.class);
                //判断命令
                switch (packet.getMsg()) {
                    //在线用户
                    case "online" :
                        //获取在线用户列表数据
                        mUserlist = packet.getList();
                        //线程更新ui
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                //用户列表适配器获取用户列表数据
                                mUserListAdapter = new UserListAdapter(mUserlist, MainActivity.this);
                                mListView.setAdapter(mUserListAdapter);
                            }
                        });
                        break;
                    //请求协助
                    case "request" :
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                //显示请求Dialog界面
                                showRequestDialog(mapper, packet);
                            }
                        });
                        break;
                    //接受协助
                    case "accept" :
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(MainActivity.this, "对方接受协助", Toast.LENGTH_SHORT).show();
                                Intent recordIntent = new Intent(MainActivity.this, RecordActivity.class);
                                //获取主机和从机id
                                recordIntent.putExtra("mid", getMid());
                                recordIntent.putExtra("sid", getSid());
                                startActivity(recordIntent);
                            }
                        });
                        break;
                    //拒绝协助
                    case "reject" :
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(MainActivity.this, "对方拒绝协助", Toast.LENGTH_SHORT).show();
                            }
                        });
                        break;
                    default:
                        break;
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    //注册信息广播接收器
    private void registerMessageBroadcastReceiver() {
        MessageBroadcastReceiver messageBroadcastReceiver = new MessageBroadcastReceiver();
        IntentFilter filter = new IntentFilter("com.example.remoteassistance.websocket.message");
        registerReceiver(messageBroadcastReceiver, filter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Intent intent = getIntent();
        //获取主机id
        setMid(intent.getStringExtra("mid"));

        //绑定数据通信websocket服务
        bindMessageWebSocketService();
        //接收用户注册广播
        registerMessageBroadcastReceiver();
        //初始化UI
        initViews();
    }

    //绑定数据通信websocket服务
    public void bindMessageWebSocketService() {
        Intent intent = new Intent(MainActivity.this, MessageWebSocketService.class);
        //获取主机id
        intent.putExtra("mid", getMid());
        //绑定服务
        bindService(intent, mMessageWebSocketServiceConnection, BIND_AUTO_CREATE);
    }

    //初始化UI界面
    private void initViews() {
        //实例化刷新视图
        mRefreshableView = (RefreshableView) findViewById(R.id.refreshable_view);
        //实例化列表视图
        mListView = (ListView) findViewById(R.id.list_view);
        //列表视图设置事件
        mListView.setOnItemClickListener(new OnItemClickListener());
        mRefreshableView.setOnRefreshListener(new RefreshableView.PullToRefreshListener() {
            @Override
            public void onRefresh() {
                try {
                    Thread.sleep(300);
                    //跟新用户列表
                    updateUserList();
                    mRefreshableView.finishRefreshing();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    //设置主机id
    private void setMid(String mid) {
        this.mid = mid;
    }

    //获取主机id
    private String getMid() {
        return mid;
    }

    //设置从机id
    private void setSid(String sid) {
        this.sid = sid;
    }

    //获取主机id
    private String getSid() {
        return sid;
    }

    //发送数据包
    public void sendMessagePacket(String msg, String mid, String sid, List<String> list, Map<String, Integer> map) {
        MessagePacket packet = new MessagePacket(msg, mid, sid, list, map);
        ObjectMapper mapper = new ObjectMapper();
        String message = null;
        try {
            //将数据打包成json格式
            message = mapper.writeValueAsString(packet);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        //通过websocket发送数据包
        mMessageWebSocketClient.send(message);
    }

    //跟新用户列表
    public void updateUserList() {
        sendMessagePacket("online", getMid(), getMid(), null, null);
    }

    //请求远程协助
    public void requestAssistance() {
        sendMessagePacket("request", getMid(), getSid(), null, null);
    }

//    public void updateUserList() {
//        ObjectMapper mapper = new ObjectMapper();
//        MessagePacket packet = new MessagePacket();
//        String msg = null;
//        packet.setMsg("online");
//        packet.setMid(getMid());
//        packet.setSid(getMid());
//        try {
//            msg = mapper.writeValueAsString(packet);
//        } catch (JsonProcessingException e) {
//            e.printStackTrace();
//        }
//        mMessageWebSocketClient.send(msg);
//    }
//
//    public void requestAssistance() {
//        ObjectMapper mapper = new ObjectMapper();
//        MessagePacket packet = new MessagePacket();
//        String msg = null;
//        packet.setMsg("request");
//        packet.setMid(getMid());
//        packet.setSid(getSid());
//        try {
//            msg = mapper.writeValueAsString(packet);
//        } catch (JsonProcessingException e) {
//            e.printStackTrace();
//        }
//        mMessageWebSocketClient.send(msg);
//    }

    //接受协助请求
    public void acceptRequest(ObjectMapper mapper, MessagePacket packet) {
        String msg = null;
        packet.setMsg("accept");
        setSid(packet.getMid());
        packet.setMid(getMid());
        packet.setSid(getSid());
        try {
            msg = mapper.writeValueAsString(packet);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        mMessageWebSocketClient.send(msg);
    }

    //拒绝协助请求
    public void rejectRequest(ObjectMapper mapper, MessagePacket packet) {
        String msg = null;
        packet.setMsg("reject");
        setSid(packet.getMid());
        packet.setMid(getMid());
        packet.setSid(getSid());
        try {
            msg = mapper.writeValueAsString(packet);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        mMessageWebSocketClient.send(msg);
    }

    //显示请求Dialog
    private void showRequestDialog(ObjectMapper mapper, MessagePacket packet) {
        AlertDialog.Builder requestDialog = new AlertDialog.Builder(MainActivity.this);
        requestDialog.setTitle("请求协助");
        requestDialog.setMessage(packet.getSid() + "向您请求协助");
        //接受按钮点击事件
        requestDialog.setPositiveButton("接受", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                //接受请求
                acceptRequest(mapper, packet);

                Intent intent = new Intent(MainActivity.this, DisplayActivity.class);
                intent.putExtra("mid", getMid());
                intent.putExtra("sid", getSid());
                //跳转到显示界面
                startActivity(intent);
            }
        });
        //拒绝按钮点击事件
        requestDialog.setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                //拒绝请求
                rejectRequest(mapper, packet);
            }
        });
        requestDialog.show();
    }

    //用户列表适配器
    private class UserListAdapter extends BaseAdapter {

        private List<String> userlist;
        private Context context;

        //侦听事件
        private OnMenuClickListener onMenuClickListener = new OnMenuClickListener();

        private class ViewHolder {
            public TextView mName;
            public View mMenu;
            public Button mRequest;
            public Button mProvide;

            public ViewHolder(View view) {
                mName = view.findViewById(R.id.item_name);
                mMenu = view.findViewById(R.id.item_menu);
                mRequest = view.findViewById(R.id.item_request);
                mProvide = view.findViewById(R.id.item_provide);
            }
        }

        public UserListAdapter(List<String> userlist, Context context) {
            this.userlist = userlist;
            this.context = context;
        }

        @Override
        public int getCount() {
            return userlist.size();
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            ViewHolder holder;
            if (view == null) {
                view = LayoutInflater.from(context).inflate(R.layout.item_user, viewGroup, false);
                holder = new ViewHolder(view);
                view.setTag(holder);
            } else {
                holder = (ViewHolder) view.getTag();
            }
            holder.mName.setText(userlist.get(i));
            holder.mMenu.setVisibility(i == mExpandedMenuPos ? View.VISIBLE : View.GONE);
            holder.mRequest.setOnClickListener(onMenuClickListener);
            holder.mProvide.setOnClickListener(onMenuClickListener);
            return view;
        }
    }

    //用户列表点击事件侦听
    private class OnMenuClickListener implements View.OnClickListener {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.item_request:
                    requestAssistance();
                    Toast.makeText(MainActivity.this, "请求协助", Toast.LENGTH_SHORT).show();
                    break;
                case R.id.item_provide:
                    Toast.makeText(MainActivity.this, "提供协助", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    }

    private class OnItemClickListener implements AdapterView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            if (i == mExpandedMenuPos) {
                mExpandedMenuPos = -1;
            } else {
                mExpandedMenuPos = i;
                setSid(mUserlist.get(i));
            }
            mUserListAdapter.notifyDataSetChanged();
        }
    }
}